<?php
namespace Fans\Controller;
use Think\Controller;
/*
	  会员登陆
*/
class LoginController extends InitController {
	


    /*
    	会员登陆页面
     */
    public function Index(){
  		$back_url = session('back_url');
		$autobaselogin = session('autobaselogin',null);
		
		$code = I('code');
		if(empty($autobaselogin) && empty($code)){
			$this->AccessLogin();
		}
		
		
		//微信授权登录
	
		if($code){
			//解析微信用户基本信息
			$appid = $this->account['appid'];
			$secret = $this->account['appsecret'];

			$weixin = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
			$curl = new  \Org\Util\Curl;
			$message_weixin = $curl->ihttp_request($weixin);

			$result         = json_decode($message_weixin['content']);
			
			if(isset($result->errcode)){
				//不声明头信息，中文有可能会出现筹码
				header("Content-type: text/html; charset=utf-8");
				echo '<h1 style="font-size:55px">授权失败'.var_dump($result->errcode).'</h1>';exit();
			}

			//获取微信授权用户信息
			$user_openid = $result->openid; 
			$access_token  = $result->access_token; 

			import('Vendor.Wechat.access');
			$wechat = new \WechatAccess();
			$token = $wechat->account_token();
			$user_info = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$user_openid}&lang=zh_CN";
			
			$result_user = $curl->ihttp_request($user_info);
			$message_user = json_decode($result_user['content']);
			$subscribe = $message_user->subscribe;
		
			if($subscribe == 0){ //没有关注的使用网页获取用户基本信息
				$user_info = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$user_openid}&lang=zh_CN";
				$result_user = $curl->ihttp_request($user_info);
				$message_user = json_decode($result_user['content']);
			}
			
			if(isset($message_user->errcode)){
				//不声明头信息，中文有可能会出现筹码
				header("Content-type: text/html; charset=utf-8");
				echo '<h1 style="font-size:55px">获取信息失败'.var_dump($message_user->errcode).'</h1>';exit();
			}
			//查询之前有没有通过微信授权登录
			$fansinfo = M('UserWxInfo')->where(" opend_id = '{$user_openid}'")->field('id,joinloginip,joinlogintime')->find();
			
			$user_name = $message_user->nickname;
			$user_sex  = $message_user->sex;
			$user_city = $message_user->city;
			$user_province = $message_user->province;
			$user_country = $message_user->country;
			$avatar       = $message_user->headimgurl;
			if(!empty($message_user->unionid)){
				$unionid = $message_user->unionid;
			}else{
				$unionid = '';
			}

			$file = get_wechat_avatarImage($avatar,$user_openid.'.jpg');

			if(!empty($fansinfo)){
				//每次授权都更新一次微信的信息
				$fans_id = $fansinfo['id'];
                $fansupdate = array(
                    'nickname'=>$user_name,
                    'sex'=>$user_sex,
                    'province'=>$user_province,
                    'city'=>$user_city,
                    'avatar'=>"/Uploads/".$file[0],
					'joinloginip'=>get_client_ip(),
					'joinlogintime'=>NOW_TIME,
					'lastloginip'=>$fansinfo['joinloginip'],
					'lastlogintime'=>$fansinfo['joinlogintime'],
                );
				M('UserWxInfo')->where(array('id'=>$fans_id))->save($fansupdate);

			}else{
			     
                //检测是否开放注册,不开放注册的情况下，不允许跳转到微信
        		$sysOpt = D('Home/Options')->getOpts(array('option_name' => 'open_reg'));
        		if ($sysOpt['open_reg']){
        			$allow_free_reg = true;
        		}else{
  		            $allow_free_reg = false;
        		}
                
                if(!$allow_free_reg){
					$this->display('no_register');die;
                }
                
                $fansinfoarray = array(
                	'opend_id'=>$user_openid,
                	'uid'=>0,
                	'nickname'=>$user_name,
                	'sex'=>$user_sex,
                    'province'=>$user_province,
                    'city'=>$user_city,
                    'avatar'=>"/Uploads/".$file[0],
                    'joinlogintime'=>time(),
					'lastlogintime'=>time(),
					'joinloginip'=>get_client_ip(),
					'lastloginip'=>get_client_ip(),
                	'createtime'=>NOW_TIME,
                );
                
                $fans_id = M('UserWxInfo')->add($fansinfoarray);
				$register_id = session('home_register_id'); //是否是有上级注册
				
				//注册有上级，上下级关系插入数据(暂时只有插入推广链接有用到这里插入)
				if($register_id){
					$data = array(
						'uid'=>0,
						'user_wx_id'=>$fans_id,
						'pid'=>$register_id,
						'createtime'=>NOW_TIME,
					);
					//中间表,用来保存上下级关系，然后在绑定手机的时候关联起来
					M('Parent')->add($data);
					session('home_register_id',null);
				}
			}

			session('autobaselogin',null);
			//跳转页面加setcookie
			$this->setcookie_wx($fans_id,true);
		}

		$back_url = session('back_url');
		session('back_url',null);
		header("location:".$back_url);
		

    }


    /*
    	会员授权登陆
    */
    public function AccessLogin(){

    	session('autobaselogin','1');
		
		$appid = $this->account['appid'];
		
		$secret = $this->account['appsecret'];
		//当前link地址
		
		$now_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		
		$now_url = urlencode($now_url);
		
		$accredit_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri={$now_url}&response_type=code&scope=snsapi_userinfo&state=accredit#wechat_redirect";

		if(IS_AJAX){
			$this->success('操作成功',$accredit_url);
		}else{
			header("location:".$accredit_url);die;
		}
    }

  	/*手机端登陆setcookie加跳转
	*$fans_id	  加密的信息
	*$url         	  当前连接
	*$jump		      true 跳转 ， false 不跳转
	*/
	private function setcookie_wx($fans_id, $jump = false){
		//把授权的openid加密
		$encrypt = wgw_encrypt($fans_id,'E','accredit');
		setcookie("wx_password",$encrypt,time()+3600,'/');

		//跳转
		if($jump){
			$back_url = session('back_url');
			session('back_url',null);
			header("Location:".$back_url);die;
		}else{
			return true;
		}

	}

	

	/*
	 * 会员退出登录
	*/
	public function Logout(){
		setcookie("wx_password",null,-100,'/');
		$_ahref = $_SERVER['HTTP_REFERER'];
		if(empty($_ahref)){
			$_ahref = "http://".$_SERVER['HTTP_HOST'].U('Mobile/Index/Index');
		}
		header('Location:'.$_ahref);
	}
}